##################################################################################################################################
#
# Copyright (C) 2008-2013 Mind System Connection. Lda. Part of Daidze Software, created by Siqsuruq. All other rights reserved.
#
# Mind System Connection Webpage: www.msysc.org
# Daidze Software Page: www.daidze.com www.daidze.org
# E-mail: admin@msysc.org, siqsuruq@gmail.com
#
##################################################################################################################################

proc sale_payment {} {
	set payment [top_win "Payment"]
	set payment_frame [ttk::frame $payment.top]
	set ::daidze_sale_pay [xml_wrapper new]
	pack $payment_frame
	
	$::daidze_sale_pay load_main pos sale_payment.xml $payment_frame
	$::daidze_sale_pay update_form [dict create total [$::daidze_main get_values list total]]
}

proc save_sale {} {
	[dict get [$::daidze_main get_fdata] sale] selection set 0 end
	set values [$::daidze_main get_values]

	set msg_list [dict create sale "You need to add at least one line to sale."]
	set flags [list]

	foreach key_val [dict keys $msg_list] {
		if {[dict get $values $key_val] == ""} {
			tk_messageBox -icon error -type ok -message "[::msgcat::mc "[dict get $msg_list $key_val]"]"
			lappend flags 0
		} else { lappend flags 1}
	}
	
	if {[lsearch -not -exact $flags 1] == "-1"} {
		$::db transaction start
		set fk_client "DAIDZE_POS"
		set inv_num [expr [$::db select_last_inserted invoice inv_num]+1]
		set custom_number "$inv_num/[now_date year]"
		set inv_date [date]
		set inv_total [dict get $values total]
		set inv_time [dict get $values inv_time]
		
		set data_inv_tbl [dict create inv_num $inv_num custom_number $custom_number fk_client $fk_client inv_time $inv_time inv_date $inv_date fk_daidze_user $daidze_users::name total $inv_total]


		# Stock part
		set stock_tmp [dict create]
		set query "SELECT id FROM stock_movement_type WHERE sale_mov = \'1\'"
		dict append stock_tmp stock_movement_type [$::db execute_query $query]
		
		# If there is no default warehouse selected trying to get default one or specific for this POS
		if {$::default_warehouse_id != 0} {
			dict append stock_tmp fk_warehouse [lindex [$::db select_all warehouse "name" "id=$::default_warehouse_id" list] 0]
		} else {
			if {[dict get $values fk_warehouse] ne ""} {
				dict append stock_tmp fk_warehouse [dict get $values fk_warehouse]
			} else {
				set warehouse [lindex [$::db select_all warehouse "name" "def=1" list] 0]
				if {$warehouse eq ""} {
					tk_messageBox -icon error -type ok -message "[::msgcat::mc "We are unable to save your invoice because you dont have warehouse define."]"
				} else {
					dict append stock_tmp fk_warehouse $warehouse
				}
			}
		}
		dict set data_inv_tbl fk_warehouse [dict get $stock_tmp fk_warehouse]
		$::db insert_all invoice $data_inv_tbl 
		
		
		dict append stock_tmp mov_date $inv_date
		dict append stock_tmp mov_time $inv_time
		dict append stock_tmp inv_num $inv_num

		set invoice_lines [dict get $values sale] 
		foreach j [dict keys $invoice_lines] g [dict values $invoice_lines] {
			dict lappend g invoice $inv_num
			dict set g discount [$::db select_id_by_name discount [dict get $g discount]]
			dict set g price [dict get $g subtotal_without_tax]
			set g [dict remove $g price_with_tax unit_tax subtotal_without_tax subtotal_with_tax]

			$::db insert_all invoice_lines $g

			# Stock movement
			if {$::stock_enable eq "yes"} {
				dict set stock_tmp qty [dict get $g qty]
				dict set stock_tmp fk_product [dict get $g fk_product]
				$::db insert_all stock_current $stock_tmp
			}
		}

		# Payment part
		set pay_values [dict create]
		dict set pay_values fk_client $fk_client
		dict set pay_values pay_date $inv_date
		dict set pay_values pay_time $inv_time
		dict set pay_values amount $inv_total

		# Default payment type block
		if {[lindex [$::daidze_sale_pay get_values list fk_payment_type] 0] eq ""} {
			# Looking for local payment type from config db
			if {$::default_payment_id != 0} {
				dict append pay_values fk_payment_type [lindex [$::db select_all payment_type "name" "id=$::default_payment_id" list] 0]
			} else {
				set query "SELECT name FROM payment_type WHERE def = \'1\'"
				set pay_type [lindex [lindex [$::db execute_query $query] 0] 0]
				if {$pay_type eq ""} {
					tk_messageBox -icon error -type ok -message "[::msgcat::mc "We are unable to save your invoice because you dont have default payment type defined."]"
				} else {
					dict set pay_values fk_payment_type $pay_type
				}
			}

		} else {
			dict set pay_values fk_payment_type [lindex [$::daidze_sale_pay get_values list fk_payment_type] 0]
		}
		dict set pay_values invoice [$::db select_last_inserted invoice inv_num]

		
		$::db insert_all payment $pay_values
		$::db transaction stop

		if {[$::daidze_sale_pay get_values list print_receipt] eq "1"} {
			set inv_id [$::db select_last_inserted invoice inv_num]
			set pay_id [$::db select_last_inserted payment id]
			::pos::print_receipt $inv_id $pay_id
		}
		destroy .topwin
		::pos::launch_pos
	}
}

proc launch_pos {} {
	set ::pos::qty 1
	$::daidze_main load_main pos pos.xml $::main 1
}

proc delete_line {{w 0}} {
	set my_tablelist [dict get [$::daidze_main get_fdata] sale]
	$my_tablelist delete [$my_tablelist curselection]
	$::daidze_main update_form [dict create total_price [round [$::daidze_main sum_tablelist_column sale 6]]]
	$::daidze_main update_form [dict create total_discount [round [$::daidze_main sum_tablelist_column sale 10]]]
	$::daidze_main update_form [dict create total_tax [round [$::daidze_main sum_tablelist_column sale 8]]]
	$::daidze_main update_form [dict create total [round [$::daidze_main sum_tablelist_column sale 11]]]
}

proc add_sale {product_name {discount_name ""} {update_sale_line ""}} {
	set my_tablelist [dict get [$::daidze_main get_fdata] sale]
	set tmp [::invoice::product_price $product_name $discount_name $::pos::qty ""]
	set line_keys [list qty fk_product price price_with_tax fk_tax unit_tax subtotal_without_tax subtotal_with_tax derived_tax discount derived_discount derived_line_total]
	foreach key $line_keys val $tmp {
		dict append line $key $val
	}

	if {$update_sale_line != ""} {
		$my_tablelist delete $update_sale_line
		set ::pos::qty 1
	}
	$::daidze_main update_form [dict create sale [dict create 0 $line] table_clear 0]
	$::daidze_main update_form [dict create total_price [round [$::daidze_main sum_tablelist_column sale 6]]]
	$::daidze_main update_form [dict create total_discount [round [$::daidze_main sum_tablelist_column sale 10]]]
	$::daidze_main update_form [dict create total_tax [round [$::daidze_main sum_tablelist_column sale 8]]]
	$::daidze_main update_form [dict create total [round [$::daidze_main sum_tablelist_column sale 11]]]
	$my_tablelist selection set end
}

proc find_by_barcode {w} {
	set barcode [$w get]
	set sdata [dict create]
	
	set query "SELECT product.name FROM product WHERE barcode=\'$barcode\' AND visible=\'1\'"
	if {[set product_list [lindex [$::db execute_query $query] 0]] ne ""} {
		set discount_name [lindex [$::daidze_main get_values list fk_discount] 0]
		set qty [lindex [$::daidze_main get_values list qty] 0]
		if {$qty != "" && $qty != 0} {
			set ::pos::qty $qty
		} else {
			set ::pos::qty 1
		}
	
		if {$::empty_stock_sale_enable eq "no"} {
			if {$::default_warehouse_id != 0} {
				set def_warehouse [lindex [$::db select_all warehouse "name" "id=$::default_warehouse_id" list] 0]
			} else {
				if {[lindex [$::daidze_main get_values list fk_warehouse] 0] ne ""} {
					set def_warehouse [$::daidze_main get_values list fk_warehouse]
				} else {
					set def_warehouse [lindex [$::db select_all warehouse name "def=1" list] 0]
				}
			}

			if {$def_warehouse ne ""} {
				set a [::stock::check_product_on_stock $def_warehouse [lindex $product_list 0]]
				if {$a >= $::pos::qty} {
					::pos::add_sale [lindex $product_list 0] $discount_name
				} else {
					tk_messageBox -icon info -type ok -message "[::msgcat::mc "Not enough quantity on stock."]"
				}
			} else {tk_messageBox -icon info -type ok -message "[::msgcat::mc "Define default warehouse or select one."]"}
		} else {
			if {$::default_warehouse_id != 0} {
				set def_warehouse [lindex [$::db select_all warehouse "name" "id=$::default_warehouse_id" list] 0]
			} else {
				if {[lindex [$::daidze_main get_values list fk_warehouse] 0] ne ""} {
					set def_warehouse [$::daidze_main get_values list fk_warehouse]
				} else {
					set def_warehouse [lindex [$::db select_all warehouse name "def=1" list] 0]
				}
			}

			if {$def_warehouse ne ""} {
				set a [::stock::check_product_on_stock $def_warehouse [lindex $product_list 0]]
				::pos::add_sale [lindex $product_list 0] $discount_name
			} else {tk_messageBox -icon info -type ok -message "[::msgcat::mc "Define default warehouse or select one."]"}
		}

	}
	$::daidze_main clear_values [list product product_search barcode fk_discount category]
}

proc value_plus_tax {no_tax tax_name} {
	set query "SELECT rate, procent FROM tax WHERE name=\'$tax_name\'"
	set prices_list [$::db execute_query $query]
	set def_tax [lindex [lindex $prices_list 0] 0]
	set tax_procent [lindex [lindex $prices_list 0] 1]
 
	if {$tax_procent == "1"} {
		set tax_val [round [expr (double($no_tax)/100) * $def_tax]]
		set with_tax [round [expr double($no_tax) + double($tax_val)]]
	} elseif {$tax_procent ne "1" && $def_tax != 0} {
		set tax_val [round $def_tax]
		set with_tax [round [expr double($no_tax) + double($tax_val)]]
	} else {
		set def_tax 0
		set with_tax [expr double($no_tax) + $def_tax]
		set tax_val $def_tax
	}
	return [list $with_tax $tax_val]
}

proc value_minus_tax {with_tax tax_name} {
	set query "SELECT rate, procent FROM tax WHERE name=\'$tax_name\'"
	set prices_list [$::db execute_query $query]
	set def_tax [lindex [lindex $prices_list 0] 0]
	set tax_procent [lindex [lindex $prices_list 0] 1]
 
	if {$tax_procent == "1"} {
		set tax_val [round [expr (double($with_tax)/(100 + $def_tax)) * $def_tax]]
		set without_tax [round [expr double($with_tax) - $tax_val]]
	} else {
		set def_tax 0
		set without_tax [expr double($with_tax) - $def_tax]
		set tax_val $def_tax
	}
	return [list $without_tax $tax_val]
}

proc find_by_category {w} {
	set cat_id [lindex [$::db select_id_by_name category [$w get]] 0]
	set product_search [lindex [$::daidze_main get_values list product_search] 0]
	if {$product_search != ""} {
		set prod_by_cat [$::db select_all product {id name fk_category default_price_with_tax} [list product.name LIKE \'$product_search%\' AND fk_category=\'$cat_id\' AND visible=\'1\']]
	} else {
		set prod_by_cat [$::db select_all product {id name fk_category default_price_with_tax} "fk_category=\'$cat_id\' AND visible=\'1\'"]
	}
	$::daidze_main update_form [dict create product $prod_by_cat table_clear 1]
}

proc find_by_name {w} {
	set category_name [lindex [$::daidze_main get_values list category] 0]
	set search_string [string map {* %} [$w get]]
	if {$category_name != ""} {
		set cat_id [lindex [$::db select_id_by_name category $category_name] 0]
		set prod [$::db select_all product {id name fk_category default_price_with_tax} [list product.name LIKE \'$search_string\' AND fk_category=\'$cat_id\' AND visible=\'1\']]
	} else {
		set prod [$::db select_all product {id name fk_category default_price_with_tax} [list product.name LIKE \'$search_string\' AND visible=\'1\']]
	}
	$::daidze_main update_form [dict create product $prod table_clear 1]
}

proc calculate_change {w} {
	set paid [$w get]
	if {$paid ne ""} {
		set change [expr $paid - [$::daidze_sale_pay get_values list total]]
		$::daidze_sale_pay update_form [dict create change $change]
	}

}

proc choose_item {w} {
	set values [dict get [dict get [$::daidze_main get_values] product] 0]

	set product_name [dict get $values fk_product]
	set discount_name [lindex [$::daidze_main get_values list fk_discount] 0]
	set qty [lindex [$::daidze_main get_values list qty] 0]
	if {$qty != "" && $qty != 0} {
		set ::pos::qty $qty
	} else {
		set ::pos::qty 1
	}

	if {$::empty_stock_sale_enable eq "no"} {
		if {$::default_warehouse_id != 0} {
			set def_warehouse [lindex [$::db select_all warehouse "name" "id=$::default_warehouse_id" list] 0]
		} else {
			if {[lindex [$::daidze_main get_values list fk_warehouse] 0] ne ""} {
				set def_warehouse [$::daidze_main get_values list fk_warehouse]
			} else {
				set def_warehouse [lindex [$::db select_all warehouse name "def=1" list] 0]
			}
		}

		if {$def_warehouse ne ""} {
			set a [::stock::check_product_on_stock $def_warehouse $product_name]
			if {$a >= $::pos::qty} {
				::pos::add_sale $product_name $discount_name
			} else {
				tk_messageBox -icon info -type ok -message "[::msgcat::mc "Not enough quantity on stock."]"
			}
		} else {tk_messageBox -icon info -type ok -message "[::msgcat::mc "Define default warehouse or select one."]"}
	} else {
		if {$::default_warehouse_id != 0} {
			set def_warehouse [lindex [$::db select_all warehouse "name" "id=$::default_warehouse_id" list] 0]
		} else {
			if {[lindex [$::daidze_main get_values list fk_warehouse] 0] ne ""} {
				set def_warehouse [$::daidze_main get_values list fk_warehouse]
			} else {
				set def_warehouse [lindex [$::db select_all warehouse name "def=1" list] 0]
			}
		}

		if {$def_warehouse ne ""} {
			set a [::stock::check_product_on_stock $def_warehouse $product_name]
			::pos::add_sale $product_name $discount_name
		} else {tk_messageBox -icon info -type ok -message "[::msgcat::mc "Define default warehouse or select one."]"}
	}

	$::daidze_main clear_values [list product product_search barcode fk_discount category qty]
}

proc print_receipt {{inv_id 0} {pay_id 0}} {
	[dict get [$::daidze_main get_fdata] sale] selection set 0 end
	set pr_data [$::daidze_main get_values list sale total_price total_discount total_tax total]
	
	set company_data [$::db select_all company {name tel fin address fax email} {def='1'} list]
	foreach company_key {company_name company_tel company_fin company_address company_fax company_email} val $company_data {
		set $company_key $val
	}

	set sale_time [$::daidze_main get_values list inv_time]
	
	set hdc [lindex [printer open] 0]
	printer job start -name gdi
	printer page start

	gdi text $hdc 10 10 -text "$company_name" -font {tahoma 8 bold} -anchor w
	gdi text $hdc 10 40 -text "Tel.:$company_tel" -font {tahoma 8} -anchor w
	gdi text $hdc 10 70 -text "NIF: $company_fin" -font {tahoma 8} -anchor w
	gdi text $hdc 10 130 -text "[::msgcat::mc "User:"] $daidze_users::name" -font {tahoma 8} -anchor w
	gdi text $hdc 10 160 -text "[::msgcat::mc "Date:"] [date] [::msgcat::mc "Time:"] $sale_time" -font {tahoma 8} -anchor w
	if {$inv_id != 0 && $pay_id != 0} {
		gdi text $hdc 10 190 -text "[::msgcat::mc "Invoice:"] $inv_id" -font {tahoma 8} -anchor w
		gdi text $hdc 10 220 -text "[::msgcat::mc "Payment:"] $pay_id" -font {tahoma 8} -anchor w
	}
	
	gdi text $hdc 10 250 -text "******************************************" -font {tahoma 8} -anchor w
	gdi text $hdc 10 280 -text "Qtd." -font {tahoma 8 bold} -anchor w
	gdi text $hdc 70 280 -text "Item" -font {tahoma 8 bold} -anchor w
	gdi text $hdc 550 280 -text "Preco" -font {tahoma 8 bold} -anchor e
	set start_y 310
	for {set x 0} {$x < [llength [lindex $pr_data 0]]} {incr x} {
		set line [lindex [lindex $pr_data 0] $x]
		gdi text $hdc 10 $start_y -text [lindex $line 0] -font {tahoma 8} -anchor w
		gdi text $hdc 55 $start_y -text [lindex $line 1] -font {tahoma 8} -anchor w
		gdi text $hdc 550 $start_y -text [lindex $line 7] -font {tahoma 8} -anchor e
		set start_y [expr $start_y + 30]
	}
	gdi text $hdc 10 $start_y -text "******************************************" -font {tahoma 8} -anchor w
	set start_y [expr $start_y + 30]
	
	gdi text $hdc 400 $start_y -text [::msgcat::mc "Subtotal:"] -font {tahoma 8 bold} -anchor e
	gdi text $hdc 550 $start_y -text [lindex $pr_data 1] -font {tahoma 8} -anchor e
	set start_y [expr $start_y + 30]
	gdi text $hdc 400 $start_y -text [::msgcat::mc "Discounts:"] -font {tahoma 8 bold} -anchor e
	gdi text $hdc 550 $start_y -text [lindex $pr_data 2] -font {tahoma 8} -anchor e
	set start_y [expr $start_y + 30]
	gdi text $hdc 400 $start_y -text [::msgcat::mc "Taxes:"] -font {tahoma 8 bold} -anchor e
	gdi text $hdc 550 $start_y -text [lindex $pr_data 3] -font {tahoma 8} -anchor e
	set start_y [expr $start_y + 30]
	gdi text $hdc 400 $start_y -text [::msgcat::mc "Total:"]  -font {tahoma 8 bold} -anchor e
	gdi text $hdc 550 $start_y -text [lindex $pr_data 4] -font {tahoma 8} -anchor e
	set start_y [expr $start_y + 60]
	gdi text $hdc 10 $start_y -text [::msgcat::mc "Thank you"]  -font {tahoma 8 bold} -anchor w

	printer page end
	printer job end
	printer close

}
